//
//  DYAFNetTool.m
//  Craft
//
//  Created by BetaTheta on 16/3/7.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "DYAFNetTool.h"
#import <AFNetworking.h>

#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "NSString+MD5.h"

@interface DYAFNetTool ()

@end

@implementation DYAFNetTool



+(void)GETNetWithUrl:(NSString *)url body:(id)body headerFile:(NSDictionary *)header response:(DYResponseStyle)responseStyle success:(BlockOfSuccess)success failure:(void (^)(NSError *))failure{
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:app.window animated:YES];//菊花
    hud.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    //    创建缓存路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //    详细路径
    NSString *chacePath = [NSString stringWithFormat:@"%@/%@.plist", path, [url md5ForString]];
    //    1.设置网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    2.设置请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    //    3.设置返回数据的类型
    switch (responseStyle) {
        case DYJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            
            break;
        case DYCML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            
            break;
        case DYDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            
            break;
        default:
            break;
    }
    //    4.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    //    5.UTF－8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //    6.请求数据
    [manager GET:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            success(responseObject);
              [NSKeyedArchiver archiveRootObject:responseObject toFile:chacePath]; // 缓存归档
            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
                sleep(1);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [hud setHidden:YES];//隐藏菊花
                    
                });
            });// 消失
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            failure(error);
            if (error) {
                id responseObject = [NSKeyedUnarchiver unarchiveObjectWithFile:chacePath];
        
                 [hud hideAnimated:YES afterDelay:3];
                
                if (responseObject) {
                    success(responseObject);
                     [hud hideAnimated:YES afterDelay:1];                }
               failure(error);
            }
        }
    }];
}


+(void)POSTNetWithUrl:(NSString *)url body:(id)body bodyStyle:(DYRequestStyle)bodyRequestStyle headerFile:(NSDictionary *)header response:(DYResponseStyle)responseStyle success:(BlockOfSuccess)success failure:(void (^)(NSError *))failure {
    //    1.设置网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //    2.设置Body体数据类型
    switch (bodyRequestStyle) {
        case DYRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            
            break;
        case DYRequestString:
            [ manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                return parameters;
            }];
            break;
            
        default:
            break;
    }
    
    
    
    
    //    2.设置请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    //    3.设置返回数据的类型
    switch (responseStyle) {
        case DYJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            
            break;
        case DYCML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            
            break;
        case DYDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            
            break;
        default:
            break;
    }
    //    4.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    //    5.UTF－8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //    6.请求数据
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            success(responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            failure(error);
        }
        
    }];
    
    
}
@end
